<template>
  <div>
    <!-- 弹窗, 新增 / 修改 -->

    <el-dialog
      title="填写信息"
      :close-on-click-modal="false"
      :visible.sync="dialogVisible"
      width="80%"
      @close="closeDialog"
      :showClose="false"
    >
      <!-- <el-button @click="$router.go(-1)" type="primary">返回</el-button> -->
      <el-form ref="form" :model="form" label-width="120px">
        <!-- 重点: 选择图片或文本 暂时注释  -->
        <!-- <el-form-item label="推送内容">
          <el-radio-group
            v-model="form.imgOrTextVal"
            @change="handleChangeImgOrText()"
          >
            <el-radio :label="0">图片</el-radio>
            <el-radio :label="1">文本</el-radio>
          </el-radio-group>
        </el-form-item> -->
        <!-- <el-form-item v-if="isImgShow"
                      label="选择活动"> -->
        <!-- <el-radio-group class="group"
                          @change="handleActSecon()"
                          v-model="form.checkedCities">
            <el-radio v-for="item in activeList"
                      :label="item.id +','+item.name"
                      :key="item.id">
              <div>
                <h5>{{item.name}}</h5>
                <img :src="item.url"
                     alt=""
                     style="width: 100%;height: 140px;">
                <div class="preview">
                  <el-button @click="handlePreview(item.id)"
                             type="text">预览</el-button>
                </div>
              </div>
            </el-radio>
          </el-radio-group> -->
        <!-- <el-button type="text" @click="handleChangeAct">选择活动</el-button> -->

        <!-- <button class="button"
                  @click="handleChangeAct">选择活动</button> -->
        <!-- </el-form-item> -->
        <el-form-item label="选择场景" v-if="isImgShow">
          <el-input :disabled="true" v-model="actVal" style="width: 300px">
          </el-input>
          <el-button type="primary" @click="handleChangeAct">{{
            actVal ? actVal : "选择"
          }}</el-button>
          <el-button @click="handleDelAct()">清空</el-button>
          <span v-if="this.form.checkedCitiesNum === 'kd_szh'">
            执行标准:
            <el-input
              class="input_num"
              placeholder=""
              style="width: 210px"
              v-model="form.calledNum"
              min="0"
              clearable
              @input="handleInput"
              type="number"
              oninput="value=value.replace(/[^0-9]/g,'')"
              v-model.number="form.calledNum"
            >
            </el-input>
          </span>
        </el-form-item>

        <el-form-item label="推送场景" v-if="!isImgShow">
          <!-- <el-select
            v-model="form.titleval"
            style="width: 300px"
            placeholder="选取推送场景"
            @change="changeTitleCon()"
          >
            <el-option
              :label="item.dictName"
              :value="item.dictName + ',' + item.remark"
              v-for="item in titleList"
              :key="item.id"
            ></el-option>
          </el-select> -->
          <el-input v-model="form.titleval" placeholder=""></el-input>
          <!-- <el-form-item label="执行标准" prop=""> -->
          <span v-if="this.form.checkedCities.split(',')[0] === 'kd_szh'">
            执行标准:<el-input
              class="input_num"
              placeholder=""
              style="width: 210px"
              v-model="form.calledNum"
              min="0"
              clearable
              oninput="value=value.replace(/[^0-9]/g,'')"
              @input="handleInput"
              type="number"
            >
            </el-input>
          </span>
          <!-- </el-form-item> -->
        </el-form-item>
        <el-form-item label="选取推送层级" v-if="pushlevelShow">
          <!-- <div  > -->
          <el-select
            v-model="form.sendUnitType"
            style="width: 300px"
            placeholder="选取层级"
            @change="changeUnitType()"
            clearable
          >
            <el-option
              :label="item.label"
              :value="item.value"
              v-for="item in pushLevel"
              :key="item.id"
            ></el-option>
          </el-select>
          <span style="color: red">
            温馨提示: "最新异动预警数据预计14:30生成"</span
          >
          <!-- </div> -->
        </el-form-item>
        <el-form-item label="活动名称" v-if="isActShow">
          <el-select v-model="form.actSecenVal" placeholder="请选择活动名称">
            <el-option
              :label="item.actName"
              :value="item.actId"
              v-for="(item, index) in actSecenlist"
              :key="index"
            ></el-option>
          </el-select>
        </el-form-item>
        <!-- <el-form-item label="监控门店类型" v-if="isTreeShow">
          <el-input
            :disabled="true"
            v-model="selectTreeData.ssName"
            style="width: 300px"
          >
          </el-input>
          <el-button
            type="primary"
            @click="handleChangeStore('监控门店类型')"
            >{{ "选择" }}</el-button
          >
          <el-button @click="handleDelAct()">清空</el-button>
        </el-form-item> -->
        <div v-if="isTreeShow && isTextShow">
          <el-form-item label="活动名称">
            <el-input
              :disabled="true"
              v-model="selectTreeData.actName"
              style="width: 300px"
            >
            </el-input>
            <el-button type="primary" @click="handleChangeActivity()">{{
              "选择"
            }}</el-button>
            <el-button @click="handleDelAct()">清空</el-button>
            <span style="color: red">
              温馨提示: "最新场景数据预计14:00生成"</span
            >
          </el-form-item>
          <el-form-item label="触发类型">
            <el-select
              v-model="dictValue"
              @change="choiceDictType(dictValue)"
              placeholder="请选择"
              clearable
              style="width: 200px"
            >
              <el-option
                :label="item.dictName"
                :value="item.dictValue"
                v-for="(item, index) in triggerList"
                :key="index"
              ></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="达标条件(户)">
            <el-input
              class="input_num"
              placeholder=""
              style="width: 210px"
              v-model="form.calledNum"
              min="0"
              clearable
              @input="handleInput"
              type="number"
              oninput="value=value.replace(/[^0-9]/g,'')"
              v-model.number="form.calledNum"
            >
            </el-input>
          </el-form-item>
        </div>
        <el-form-item label="推送标题" v-if="!isImgShow">
          <el-input
            v-model="form.titleName"
            placeholder="请输入标题"
            :disabled="getDisabled(isTrue)"
            maxlength="20"
            show-word-limit
          ></el-input>
        </el-form-item>
        <el-form-item
          label="推送内容"
          v-if="!contentShow"
          style="position: relative"
        >
          <el-input
            type="textarea"
            v-model="form.desc"
            placeholder="请输入要推送的内容，只支持文本"
            :disabled="getDisabled(isTrue)"
            maxlength="200"
            show-word-limit
            @blur="testBlur"
            ref="textarea"
          ></el-input>
          <el-button
            type="primary"
            v-if="pushlevelShow"
            class="charuBianLiang"
            @click="bianliangBtn()"
            size="mini"
            >插入变量</el-button
          >
          <el-button
            type="success"
            v-if="pushlevelShow"
            size="mini"
            class="charuImgas"
            @click="imgsBtn()"
            >查看图片</el-button
          >
        </el-form-item>
        <el-form-item v-if="!imageShow">
          <div v-if="this.imagesType === '2'">
            <div>
              <img
                src="http://134.64.251.212:8084/cpcp/imgUrl/two.png"
                alt=""
              />
            </div>
            <div style="margin-top: 5px">
              <img
                src="http://134.64.251.212:8084/cpcp/imgUrl/three.png"
                alt=""
              />
            </div>
          </div>
          <div v-if="this.imagesType === '3'">
            <img
              src="http://134.64.251.212:8084/cpcp/imgUrl/three.png"
              alt=""
            />
          </div>
          <div v-if="this.imagesType === '4'">
            <img src="http://134.64.251.212:8084/cpcp/imgUrl/four.png" alt="" />
          </div>
        </el-form-item>
        <el-form-item label="推送内容" v-if="!tinymceisImgShow">
          <editor
            id="tinymce"
            @compositionstart="compositionstart"
            v-model="form.desc"
            :init="init"
          ></editor>
          <!-- <button @click="btn">点击</button> -->
        </el-form-item>
        <div v-if="upgradeShow">
          <el-form-item label="是否向上升级">
            <el-radio
              v-model="form.isUpgrade"
              label="1"
              @change="changeRadio(form.isUpgrade)"
              >是</el-radio
            >
            <el-radio
              v-model="form.isUpgrade"
              label="0"
              @change="changeRadio(form.isUpgrade)"
              >否</el-radio
            >
          </el-form-item>
        </div>
        <el-form-item
          label="升级条件"
          v-if="
            form.isUpgrade == '1' &&
            (form.sendUnitType === '4' || form.sendUnitType === '5')
          "
        >
          <el-select v-model="form.filterType" placeholder="请选择升级条件">
            <el-option
              :label="item.label"
              :value="item.value"
              v-for="(item, index) in upgradeData"
              :key="index.value"
            ></el-option>
          </el-select>
          触发条件：
          <el-select v-model="form.filterCondit" placeholder="请选择触发条件">
            <el-option
              :label="item.label"
              :value="item.value"
              v-for="(item, index) in triggerData"
              :key="index.value"
            ></el-option>
          </el-select>
          <el-input-number
            v-model="form.threshold"
            :min="0"
            :max="100"
            :controls="false"
            :precision="2"
            style="width: 150px"
          ></el-input-number>
          <el-button type="primary" size="mini" round>%</el-button>
          <!-- <el-button type="primary" size="mini" round>确定</el-button> -->
        </el-form-item>
        <div
          v-if="
            form.isUpgrade == '1' &&
            (form.sendUnitType === '4' || form.sendUnitType === '5')
          "
        >
          <el-form-item label="推送升级标题" v-if="!isImgShow">
            <el-input
              v-model="form.upgradeTitle"
              placeholder="请输入推送升级标题"
              :disabled="getDisabled(isTrue)"
              maxlength="20"
              show-word-limit
            ></el-input>
          </el-form-item>
          <el-form-item
            label="推送升级内容"
            v-if="!contentShow"
            style="position: relative"
          >
            <el-input
              type="textarea"
              v-model="form.upgradeContent"
              placeholder="请输入要推送的内容"
              :disabled="getDisabled(isTrue)"
              maxlength="200"
              show-word-limit
            ></el-input>
            <el-button
              type="success"
              v-if="pushlevelShow"
              size="mini"
              class="ShengImgas"
              @click="imgsShengBtn()"
              >查看升级图片</el-button
            >
          </el-form-item>
          <el-form-item v-if="!imageShengShow">
            <div v-if="this.imagesShengType === '4'">
              <img
                src="http://134.64.251.212:8084/cpcp/imgUrl/four.png"
                alt=""
              />
            </div>
            <div v-if="this.imagesShengType === '5'">
              <img
                src="http://134.64.251.212:8084/cpcp/imgUrl/five.png"
                alt=""
              />
            </div>
          </el-form-item>
        </div>
        <el-form-item label="推送图片" v-if="!tinymceisImgShow">
          <el-upload
            :action="imgAction"
            list-type="picture-card"
            :file-list="fileList"
            name="images"
            :on-preview="handlePictureCardPreview"
            :on-remove="handleRemove"
            :on-success="handleSuccess"
            :limit="5"
            :on-exceed="handleExceed"
          >
            <i class="el-icon-plus"></i>
          </el-upload>
        </el-form-item>
        <div style="display: flex">
          <el-form-item label="推送方式">
            <el-select v-model="form.mode" placeholder="请选择推送方式">
              <el-option label="推送升级" value="1"></el-option>
              <el-option label="普通推送" value="0"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="推送时间">
            <el-radio-group
              v-model="pushTimeType"
              @change="handleChangepushType()"
            >
              <el-radio :label="1">立即推送</el-radio>
              <el-radio :label="0">定时发送</el-radio>
            </el-radio-group>
            <!-- <el-date-picker v-if="isTimeShow"
                            v-model="form.timeVal"
                            value-format="yyyy-MM-dd HH:mm:ss"
                            type="datetime"
                            :picker-options="pickerOptions1"
                            placeholder="选择日期时间">
            </el-date-picker> -->
          </el-form-item>
          <el-form-item label="推送周期" v-if="isCycle">
            <el-select
              v-model="cycle"
              placeholder="请选择推送周期"
              style="width: 150px"
              @change="handleCycle()"
            >
              <el-option
                :label="item.dictName"
                v-for="item in cycleList"
                :key="item.id"
                :value="item.id"
              ></el-option>
            </el-select>
            <el-time-picker
              v-if="isTimeShow"
              style="width: 120px"
              v-model="form.timeVal"
              :picker-options="{
                start: '00:00',
                step: '00:15',
                end: '23:59',
              }"
              format="HH:mm"
              value-format="HH:mm"
              placeholder="选择时间"
            >
            </el-time-picker>
            <el-date-picker
              v-if="isDateTimeShow"
              v-model="form.timeVal"
              type="datetime"
              format="yyyy:MM:dd HH:mm"
              value-format="yyyy:MM:dd:HH:mm"
              placeholder="选择日期时间"
            >
            </el-date-picker>
          </el-form-item>
        </div>
        <div v-if="whetherShow">
          <el-form-item label="是否升级对象">
            <el-radio v-model="form.whether" label="1">是</el-radio>
            <el-radio v-model="form.whether" label="2">否</el-radio>
          </el-form-item>
        </div>
        <div v-if="isObjectShow">
          <div style="display: flex">
            <el-form-item label="推送对象">
              <!-- <el-button type="text"
                       @click="handleChangeGroup()">{{changeName}}</el-button> -->
              <el-button
                type="text"
                @click="handleChangelable(0, '选择主数据人员', 1)"
                v-if="this.form.whether == '2'"
                >选择主数据人员</el-button
              >
              <el-button
                type="text"
                @click="handleChangelable(0, '选择主数据群组', 2)"
                v-if="this.form.whether == '2'"
                >选择主数据群组</el-button
              >
              <el-button
                type="text"
                @click="handleChangelable(1, '选择Iwork群组', 3)"
                v-if="this.form.whether == '2'"
                >选择Iwork群组</el-button
              >
              <el-button
                type="text"
                @click="handleChangelable(0, '渠道视图', 4)"
                v-if="isTreeShow && this.form.whether == '2'"
                >选择渠道视图</el-button
              >
              <el-upload
                v-if="isTreeShow && this.form.whether == '1'"
                style="display: inline-block; line-height: 28px"
                name="file"
                ref="upload"
                :multiple="true"
                :show-file-list="false"
                :onError="uploadError"
                :onSuccess="uploadSuccess"
                :action="actionUp"
                :auto-upload="true"
                :data="iconFileData"
              >
                <el-button
                  style="margin: 0, 10px"
                  type="success"
                  @click="handleChangelable(0, 'EXCEL导入数据人员', 5)"
                  >EXCEL上传</el-button
                >
              </el-upload>
              <!-- <el-button
                type="success"
                @click="handleChangelable(0, '渠道视图', 4)"
                
                >EXCEL导入</el-button
              > -->
              <el-button
                type="info"
                @click="downLoad"
                v-if="isTreeShow && this.form.whether == '1'"
                >推送模板下载</el-button
              >
            </el-form-item>
          </div>
          <el-form-item label="已选人员" v-if="isRealy">
            <el-input
              type="textarea"
              style="width: 80%"
              :rows="2"
              :disabled="true"
              placeholder="请输入内容"
              v-model="personList"
            >
            </el-input>
          </el-form-item>
          <el-form-item
            label="升级人员"
            v-if="isTreeShow && this.form.whether == '1'"
          >
            <el-input
              type="textarea"
              style="width: 80%"
              :rows="2"
              :disabled="true"
              placeholder="请输入内容"
              v-model="shengjiList"
            >
            </el-input>
          </el-form-item>
          <el-form-item label="已选主数据群组" v-if="isPerson">
            <el-input
              :disabled="true"
              v-model="relaryLableName"
              style="width: 300px"
            >
            </el-input>
            <el-button @click="handleNoGroup()">清空</el-button>
          </el-form-item>
          <el-form-item label="已选Iwork群组" v-if="isIwork">
            <el-input
              :disabled="true"
              style="width: 300px"
              v-model="relaryGroupName"
            >
            </el-input>
            <el-button @click="handleIworkNoGroup()">清空</el-button>
          </el-form-item>
        </div>
      </el-form>
      <div class="handleSave_btn">
        <span slot="footer" class="dialog-footer">
          <!-- <el-button @click="close">取消</el-button> -->
          <el-button @click="handleSave" type="success">保存</el-button>
        </span>
      </div>
    </el-dialog>
    <!-- 选择人弹框 -->
    <sendDialog
      ref="send"
      @fetchPersonId="fetchPersonId(arguments)"
    ></sendDialog>
    <!-- 监控门店类型 -->
    <storeDialog
      ref="storeDialog"
      @fetchPersonId="getTreeMenDianData"
    ></storeDialog>
    <!-- 活动名称弹框 -->
    <activityDialog
      ref="activityDialog"
      @fetchPersonId="getTreeHuoDongData"
    ></activityDialog>
    <!-- 查看图片 -->
    <el-dialog :visible.sync="isUploadImgShow" width="50%">
      <img width="100%" :src="dialogImageUrl" alt="" />
    </el-dialog>
    <!-- 选择群组 -->
    <el-dialog
      title="Iwork群组"
      :close-on-click-modal="false"
      :visible.sync="isGroupDialog"
      width="50%"
    >
      <div style="text-align: center; margin: 80px 0">
        <el-select
          v-model="groupIdVal"
          style="width: 300px"
          placeholder="选择Iwork群组"
        >
          <el-option
            :label="item.dictName"
            :value="item.dictName + ',' + item.dictValue"
            v-for="(item, index) in groupList"
            :key="index"
          ></el-option>
        </el-select>
        <el-button type="primary" @click="handleChangeGroupId()"
          >确定</el-button
        >
      </div>
    </el-dialog>
    <!-- 选择标签 -->
    <el-dialog
      title="选择主数据群组"
      :close-on-click-modal="false"
      :visible.sync="isLableDialog"
      width="50%"
    >
      <div style="text-align: center; margin: 80px 0">
        <el-select
          v-model="lableVal"
          placeholder="选择主数据群组"
          style="width: 300px"
        >
          <el-option
            :label="item.dictName"
            :value="item.dictName + ',' + item.id"
            v-for="(item, index) in lableList"
            :key="index"
          ></el-option>
        </el-select>
        <el-button type="primary" @click="handLableId()">确定</el-button>
      </div>
    </el-dialog>
    <!-- 选择活动弹框 -->
    <el-dialog
      title="选择活动"
      :close-on-click-modal="false"
      :visible.sync="isActDialog"
      width="60%"
    >
      <el-table
        :data="actImgTableData"
        stripe
        border
        style="width: 100%; margin-top: 10px"
      >
        <el-table-column
          prop="dictValue"
          align="center"
          width="120"
          label="场景编码 "
        >
        </el-table-column>
        <el-table-column prop="dictName" align="center" label="场景名称">
        </el-table-column>
        <el-table-column label="图片" align="center" width="160">
          <template slot-scope="scope">
            <img
              :src="fetchImg(scope.row.uploadPath)"
              alt=""
              v-if="scope.row.uploadPath"
              @click="handleLookImg(scope.row.uploadPath)"
              class="sm_img"
            />
          </template>
        </el-table-column>
        <el-table-column prop="name" align="center" label="操作 ">
          <template slot-scope="scope">
            <el-button
              @click="handleChangeActivte(scope.row)"
              type="text"
              size="small"
              >选择</el-button
            >
          </template>
        </el-table-column>
      </el-table>
    </el-dialog>
    <!-- 预览弹框 -->
    <el-dialog
      title="预览"
      :close-on-click-modal="false"
      :visible.sync="previewDialog"
      width="60%"
    >
      <div class="preview_img">
        <img :src="previewUrl" alt="活动" />
      </div>
    </el-dialog>
    <!-- 插入变量的弹框 -->
    <el-dialog
      title="选取推送变量"
      :close-on-click-modal="false"
      :visible.sync="bianliangShow"
      width="25%"
      class="tuiSong_dialog"
    >
      <div class="checkList_box">
        <div v-for="item in variableData" :key="item.colum">
          <el-checkbox-group v-model="checkList">
            <el-checkbox :label="item.colum">{{
              item.note + "--" + item.colum
            }}</el-checkbox>
          </el-checkbox-group>
          <!-- <el-checkbox v-model="item.colum">{{ item.note }}</el-checkbox> -->
        </div>
      </div>
      <div class="onSubmit_button">
        <el-button type="primary" @click="onSubmit">确定选择</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import sendDialog from "../components/sendDialog copy";
import storeDialog from "../components/storeDialog copy";
import activityDialog from "../components/activityDialog";
import axios from "axios";
import img_1 from "../../../assets/img/01.png";
import img_2 from "../../../assets/img/02.png";
import img_3 from "../../../assets/img/03.png";
import img_4 from "../../../assets/img/04.png";
import tinymce from "tinymce/tinymce";
import Editor from "@tinymce/tinymce-vue";
import "tinymce/themes/silver/theme";
import "tinymce/plugins/colorpicker"; //选择颜色插件
import "tinymce/plugins/textcolor"; //文本颜色插件
import "tinymce/plugins/image";
import "tinymce/plugins/link";

//引入图标
import "tinymce/icons/default";
// 主要是解决打包到线上访问不到 static tinymce 下文件访问不到问题
const url = window.SITE_CONFIG.version ? "/" + window.SITE_CONFIG.version : "";
export default {
  data() {
    return {
      staffAccountToken: null,
      apiKey: null,
      sanToken: null,
      isYdWarn: null, //编辑带回来的字段，用于判断那个编辑场景，和那个保存场景
      ydExpandId: "", //移动预警编辑使用字段
      action: "", //推送模板下载
      actionUp: "", //excel上传
      iconFileData: {
        //文件上传所需要的参数
        file: "",
      },
      uploadForm: {
        //execl上传后返回的数据
        batchId: "",
        pushNames: "",
        upgradeNames: "",
      },
      tinymceHtml: "",
      init: {
        language: "zh_CN", //语言
        language_url: url + "/static/tinymce/zh_CN.js", //语言包的路径
        skin_url: url + "/static/tinymce/skins/ui/oxide",
        //content_css可设置编辑区内容展示的css，谨慎使用
        content_css: url + "/static/tinymce/skins/content/dark/content.css", //输入框的样式
        height: 300, //编辑器高度
        zindex: 100,
        plugins: "link image",
        toolbar:
          "'undo redo |  formatselect | bold italic | alignleft aligncenter alignright alignjustify | bullist numlist outdent indent | image link | removeformat'",
        // images_upload_handler: (blobInfo, success, failure) => {
        // const img = 'data:image/jpeg;base64,' + blobInfo.base64()
        // success(img)
        // }
      },
      selectTreeData: {
        ssName: "", //选任人员组件带过来的名字
        ssCode: "", //选任人员组件带过来的工号
        actName: "", //活动名称组件带过来的名称
        actId: "", //活动名称组件带过来的活动id
      },
      dataList: [],
      triggerList: [], //触发类型下拉框数据
      dictValue: "",
      isChecked: 0,
      isAllCampaign: 0,
      treeHuongDongData: [], //活动名称选人保存的值，用于再次选择带回去值
      menDianTreeData: [], //监控门店类型选人保存的值，用于再次选择带回去值
      isTrue: true,
      pageNum: 1,
      pageSize: 10,
      total: 0,
      latnIdList: [],
      latnId: "", //当前登录人的地市code
      groupList: [],
      lableList: [],
      actTableData: [],
      actImgTableData: [],
      isOnlySceneData: [
        { label: "否", value: "0" },
        { label: "是", value: "1" },
      ],
      actVal: "",
      dialogVisible: false,
      id: null,
      previewUrl: "",
      previewDialog: false,
      bianliangShow: false,
      isActDialog: false,
      isAct: false,
      isImgShow: true,
      contentShow: true,
      imageShow: true,
      imageShengShow: true, //升级图片显隐
      tinymceisImgShow: true, //富文本编辑器显隐
      isGroupDialog: false,
      isLableDialog: false,
      isPerson: false,
      isIwork: false,
      isRealy: true,
      groupIdVal: "",
      lableVal: "",
      personList: "", //已选人员
      shengjiList: "", //升级人员
      relaryGroupName: "",
      relaryLableName: "",
      titleList: [],
      isCycle: true,
      cycle: "",
      isTimeShow: true,
      isDateTimeShow: false,
      isActShow: false,
      isObjectShow: false,
      isTreeShow: false, // 主要控制个性化触发场景的显示条件
      isTextShow: false,
      cycleList: [],
      imgAction: "", // 上传图片地址
      isUploadImgShow: false,
      fileList: [],
      dialogImageUrl: "",
      changeName: "选择主数据人员",
      ids: [],
      dataForm: {
        sendType: "",
        masterValue: "",
        iworkValue: "",
        numVaue: "",
        nameValue: "",
        secenValue: "",
        isOnlyScene: "", //场景是否唯一
        staffValue: "",
      },
      pushTimeType: 1,
      // isTimeShow: true,
      form: {
        mode: "0",
        pattern: "0",
        company: "",
        isPush: true,
        checkedCities: "",
        imgOrTextVal: 1,
        timeVal: "",
        titleval: null,
        titleName: "",
        desc: "",
        groupId: "",
        groupName: "",
        lableName: "",
        lableId: "",
        // titleList: [],
        actSecenlist: [],
        actSecenVal: "",
        calledNum: 5,
        dabiaoNum: 5,
        checkedCitiesNum: "",
        whether: "2", //是否是升级对象
        isUpgrade: "0", //是否向上升级
        sendUnitType: "", //选取推送层级
        unitType: "", //点击插入变量时候传的参数
        filterType: "", //升级条件
        filterCondit: "", //判断条件
        threshold: 5, //触发条件
        threSymbol: "", //触发条件前面的符号
        upgradeTitle: "", //du升级人员标题
        upgradeContent: "", //du升级人员内容
      },
      pushlevelShow: false,
      pushLevel: [
        //选取推送层级
        {
          value: "2",
          label: "二级单元",
        },
        {
          value: "3",
          label: "三级单元",
        },
        {
          value: "4",
          label: "四级单元",
        },
        {
          value: "5",
          label: "五级单元",
        },
      ],
      upgradeData: [
        { label: "日加约率", value: "0" },
        { label: "日接触率", value: "1" },
        { label: "日离网率", value: "2" },
        { label: "月加约率", value: "3" },
        { label: "月接触率", value: "4" },
        { label: "月离网率", value: "5" },
        { label: "全部加约率", value: "6" },
        { label: "全部接触率", value: "7" },
        { label: "全部离网率", value: "8" },
      ], //升级条件
      triggerData: [
        { label: "<", value: "0" },
        { label: "<=", value: "1" },
        { label: ">", value: "2" },
        { label: ">=", value: "3" },
        { label: "=", value: "4" },
      ],
      threshold: [">", "=", "<", ">=", "<="], //阈值前面的>=<号
      variableData: [], //推送内容里面插入的变量
      checkList: [], //插入变量选中的值
      whetherShow: false, //是否是升级对象的显隐
      upgradeShow: false, //是否向上升级的显隐
      imagesType: "0", //点击查看图片
      imagesShengType: "0", //点击查看升级图片
      pickerOptions1: {
        disabledDate(time) {
          return time.getTime() < Date.now() - 8.64e7;
        },
      },
      userType: null, // 保存是德类型 1：选择主数据人员 2：选择主数据群组， 3： 选择iwork群组 4：选择渠道视图 ，5：excel导入数据人员 ，6：移动预警标签
      sendStaffAccount: "", //人员sendStaffAccount
      blurIndex: null, // 光标位置
    };
  },
  computed: {
    cityCode: {
      get() {
        return this.$store.state.user.cityId;
      },
      set(val) {
        this.$store.commit("user/updateCityCode", val);
      },
    },
    // lableList: {
    //   get () {
    //     return this.$store.state.type.du_user_tag
    //   }
    // },
    // titleList: {
    //   get () {
    //     return this.$store.state.type.du_text
    //   }
    // }
  },
  activated() {
    // this.fetchGroupList();
    // this.fetchCycleData();
    // this.fetchTitleList();
    // this.fetchLableList();
    // this.fetchActSecen();
    // this.fetchActData();
    // this.getTriggerList();
    // this.getImgSecenData();
  },
  created() {
    // this.imgAction = this.$http.adornUrl(
    //   `cpcpdu/uploadImg?token=${this.$cookie.get("token")}`
    // );
    // this.fetchTableList();
    // this.action = this.$http.adornUrl(`staffConfig/downFile?type=1`);
    // this.actionUp = this.$http.adornUrl(
    //   `staffConfig/importPushDate?token=${this.$cookie.get("token")}`
    // );
    this.getUrl();
    // this.fetchGroupList();
    // this.fetchCycleData();
    // this.fetchTitleList();
    // this.fetchLableList();
    // this.fetchActSecen();
    // this.fetchActData();
    // this.getTriggerList();
    // this.getImgSecenData();
    // this.handleAdd();
    // alert(this.action)
    // this.fetchTitleList()
    // this.fetchLableList()
    // this.fetchActSecen()
    // this.getVariable();
  },
  components: {
    sendDialog,
    storeDialog,
    activityDialog,
    Editor,
  },
  mounted() {
    tinymce.init({});
  },
  methods: {
    getUrl() {
      // let url = window.location.href;
      let url = window.location.href;
      // console.log("staffAccount=", this.$route.params.staffAccount);
      // console.log("apiKey=", this.$route.params.apiKey);
      console.log("url=", url);
      // console.log("url.indexOf('token')==", url.indexOf("token"));
      // console.log("url.indexOf('token')==", url.indexOf("token"));
      // console.log("url.indexOf('token')==", url.indexOf("token"));
      console.log("------------------------", this.$cookie.get("token"));
      var reg = url.substring(url.indexOf("?") + 1, url.length).split("&");
      console.log("=====================", reg);
      let list = [];
      let obj = {};
      reg.forEach((item) => {
        let data = item.split("=");
        let x = data[0];
        obj[x] = data[1];
        list.push(obj);
      });
      console.log("listlistlistlistlist", list);
      // console.log("staffAccount==========",list[0].staffAccount);
      // console.log("apiKey==========",list[1].apiKey);
      // let listData = list.sort()
      const newArr = Array.from(new Set(list));
      console.log("newArrnewArrnewArrnewArr==", newArr);
      newArr.forEach((element) => {
        // console.log("element=====",element);
        console.log("element=====", element.staffAccount);
        this.staffAccountToken = element.staffAccount;
        this.apiKey = element.apiKey;
        console.log("element=====", element.apiKey);
        console.log("element=====", element.name);
        // this.getToken(this.staffAccountToken)
      });
      // if (this.$cookie.get("token")) {
      console.log("token存在");
      this.getToken(this.staffAccountToken);
      // this.$router.replace({ name: "inventoryAddorUpdate" });
      // this.$cookie.set("token", this.sanToken);
      // console.log();

      // } else {
      console.log("token不存在");
      console.log("this.staffAccountToken===", this.staffAccountToken);
      // this.getToken(this.staffAccountToken);
      // this.$cookie.set("token", this.sanToken);
      // this.$router.replace({ name: "inventoryAddorUpdate" });
      // }
    },
    getToken(staffAccount) {
      this.$http({
        url: this.$http.adornUrl("/createTripartiteToken"),
        method: "get",
        params: this.$http.adornParams({
          staffAccount: staffAccount,
        }),
      }).then((res) => {
        console.log("res======", res);
        console.log("res======", res.data.data.userInfo.latnId);
        console.log("res.data.data.token", res.data.data.token);
        this.latnId = res.data.data.userInfo.latnId;
        this.sanToken = res.data.data.token;
        this.$cookie.set("token", this.sanToken);
        this.fetchGroupList();
        this.fetchCycleData();
        this.fetchTitleList();
        this.fetchLableList();
        this.fetchActSecen();
        this.fetchActData();
        this.getTriggerList();
        this.getImgSecenData();
        this.handleAdd();
        // console.log("this.$cookie.get('token');",this.$cookie.get("token"));
      });
    },
    handleExceed(file) {
      this.$message.error("最多上传5张图片");
    },
    handleSuccess(file) {
      let obj = {};
      obj.url = file.data;
      this.fileList.push(obj);
    },
    handleRemove(file, fileList) {
      this.fileList = fileList;
    },
    handlePictureCardPreview(file) {
      this.isUploadImgShow = true;
      this.dialogImageUrl = file.url;
    },
    compositionstart(e) {},
    handleLookImg(url) {
      this.previewDialog = true;
      this.previewUrl = this.$http.adornUrl(url);
    },
    handleDelAct() {
      this.actVal = "";
      this.form.checkedCities = "";
      this.selectTreeData.ssName = "";
      this.selectTreeData.ssCode = "";
      this.selectTreeData.actId = "";
      this.selectTreeData.actName = "";
      this.isObjectShow = false;
    },
    handleChangeActivte(data) {
      this.form.checkedCities = `${data.dictValue},${data.dictName}`;
      this.actVal = data.dictName;
      this.handleActSecon();
      this.isActDialog = false;
    },
    fetchImg(url) {
      return this.$http.adornUrl(url);
    },
    // 选择活动
    handleChangeAct() {
      this.isActDialog = true;
      //   this.$http({
      //   url: this.$http.adornUrl("/cpcpscenerole/getSceneList"),
      //   method: "get",
      //   params: this.$http.adornParams({
      //     dictDataType: "send_activity",
      //   }),
      // }).then(res => {
      // })
    },

    //获取到监控门店类型树结构传过来的值
    getTreeMenDianData(data) {
      // this.menDianTreeData = menDianTreeData;
      let list = data;
      this.personList = "";
      let treeDatassCode = "";
      list.map((item) => {
        this.personList += item.ssName + ",";
        treeDatassCode += item.ssCode + ",";
      });
      this.selectTreeData.ssCode = treeDatassCode.substring(
        0,
        treeDatassCode.length - 1
      );
    },
    //获取到活动名称树结构传过来的值
    getTreeHuoDongData(treeHuongDongData, isAllCampaign) {
      if (isAllCampaign === false) {
        this.isAllCampaign = 0;
      } else {
        this.isAllCampaign = 1;
      }
      this.treeHuongDongData = treeHuongDongData;
      this.selectTreeData.actName = ""; //当选人后再继续选择时，这是要清除之前拼接的人员
      this.selectTreeData.actId = "";
      let treeHuongDongDataActid = "";
      this.treeHuongDongData.map((item) => {
        this.selectTreeData.actName += item.actName + ",";
        treeHuongDongDataActid += item.actId + ",";
        this.selectTreeData.actId = treeHuongDongDataActid.substring(
          0,
          treeHuongDongDataActid.length - 1
        );
      });
    },
    //活动名称弹框
    handleChangeActivity() {
      this.$nextTick(() => {
        this.$refs.activityDialog.init(
          this.id,
          this.treeHuongDongData,
          this.isAllCampaign
        );
      });
    },
    //触发类型下拉框
    getTriggerList() {
      this.loading = true;
      this.$http({
        url: this.$http.adornUrl(`sysdictdata/list`),
        method: "get",
        params: this.$http.adornParams({
          page: 1,
          limit: 10,
          dictType: "du_standard_type",
        }),
      }).then(({ data }) => {
        if (data.code === 0) {
          this.triggerList = data.page.list;
        }
      });
    },
    choiceDictType(dictValue) {
      this.dictValue = dictValue;
    },
    // 获取搜索条件下拉场景数据
    fetchActData() {
      this.$http({
        url: this.$http.adornUrl("/sysdictdata/getList"),
        method: "get",
        params: this.$http.adornParams({
          dictType: "send_activity",
          isShow: 1,
        }),
      }).then(({ data }) => {
        if (data && data.code === 0) {
          this.actTableData = data.list;
        }
      });
    },
    // 获取图片场景数据
    getImgSecenData() {
      this.$http({
        url: this.$http.adornUrl("/sysdictdata/getImgSceneList"),
        method: "get",
        params: this.$http.adornParams({
          dictType: "send_activity",
          isShow: 1,
        }),
      }).then(({ data }) => {
        if (data && data.code === 0) {
          this.actImgTableData = data.list;
        }
      });
    },
    // 开启或者关闭
    handleOpenOrClose(id, status) {
      let title = status === 1 ? "开启" : "关闭";
      this.$confirm(`您确定要${title}吗`, "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          this.$http({
            url: this.$http.adornUrl("cpcpdu/openOrClose"),
            method: "post",
            data: this.$http.adornData({
              id: id,
              status: status,
            }),
          }).then(({ data }) => {
            if (data && data.code === 0) {
              this.$message({
                message: "操作成功",
                type: "success",
              });
              this.fetchTableList();
            } else {
              this.$message.error(data.msg);
            }
          });
        })
        .catch(() => {});
    },
    getSendObject(item) {
      let str = "";
      if (item.sendGroup == 1) {
        str = item.groupName;
      } else {
        if (null != item.labelName) {
          str = item.labelName;
        } else {
          str = "个人";
        }
      }
      return str;
    },
    handleActSecon() {
      //控制编辑时候回显的页面先隐
      let val = this.form.checkedCities.split(",");
      this.contentShow = false;
      if (val[0] === "hdcf" || val[0] === "hdsx") {
        this.isActShow = true;
      } else {
        this.isActShow = false;
        this.form.actSecenVal = "";
      }
      if (val[0] === "cswbts") {
        this.whetherShow = true; //点击编辑的时候：是否升级对象的显示
        this.tinymceisImgShow = false;
        this.contentShow = true;
      } else {
        this.tinymceisImgShow = true;
      }
      if (
        val[0] === "hdcf" ||
        val[0] === "xs_bqzd" ||
        val[0] === "yh_bqzd" ||
        val[0] === "xs_kb" ||
        val[0] === "xs_kbzd" ||
        val[0] === "yh_kbzd" ||
        val[0] === "5G_hj" ||
        val[0] === "cswbts" ||
        val[0] === "gxh_scene"
      ) {
        this.isObjectShow = true;
      } else {
        this.isObjectShow = false;
      }
      this.form.checkedCitiesNum = val[0];
    },
    // 获取活动差分场景
    fetchActSecen() {
      this.$http({
        url: this.$http.adornUrl("generator/cpcpsplit/getActivitySplitList/"),
        method: "get",
        params: this.$http.adornParams({}),
      }).then(({ data }) => {
        {
          if (data && data.code === 0) {
            this.actSecenlist = data.list;
          }
        }
      });
    },
    // 主数据群组人员回显
    fetchAgainGroupData(sysDictDataId) {
      this.$http({
        url: this.$http.adornUrl("/staffsysdictdata/getStaffList"),
        method: "get",
        params: this.$http.adornParams({
          sysDictDataId: sysDictDataId,
        }),
      }).then(({ data }) => {
        if (data && data.code === 0) {
          let list = [];
          if (data.list) {
            data.list.map((item) => {
              list.push(item.staffName);
            });
          }
          this.personList = list.toString();
        }
      });
    },
    handleCycle() {
      if (this.cycle == "17") {
        this.isTimeShow = true;
        this.isDateTimeShow = false;
      } else {
        this.isTimeShow = false;
        this.isDateTimeShow = true;
      }
    },
    fetchCycleData() {
      this.$http({
        url: this.$http.adornUrl("/sysdictdata/list"),
        method: "get",
        params: this.$http.adornParams({
          dictType: "send_time_type",
        }),
      }).then(({ data }) => {
        if (data && data.code === 0) {
          // this.cycleList = data.page.list;
          // this.cycle = this.cycleList[0].id;
          // if (this.form.titleval === "异动预警-疑似异网营销") {
          console.log("cycleList======", this.cycleList);
          let objectT = data.page.list.find((item) => {
            return item.dictName === "日";
          });
          console.log(objectT);
          this.cycle = objectT.id;
          this.cycleList = [];
          this.cycleList.push(objectT);
          console.log("-----", this.cycleList);
          // }
        }
      });
    },
    handleNoGroup() {
      this.lableVal = "";
      this.personList = "";
      this.relaryLableName = "";
    },
    handleIworkNoGroup() {
      this.groupIdVal = "";
      this.personList = "";
      this.relaryGroupName = "";
    },
    handleChangelable(val, name, userType) {
      this.form.pattern = val;
      this.userType = userType;
      console.log("this.userType==", this.userType);
      this.changeName = name;
      if (name === "选择主数据人员") {
        this.$refs.send.init("选择主数据人员", this.id, this.form.groupId);
      }
      if (name === "选择主数据群组") {
        this.isLableDialog = true;
      }
      if (name === "选择Iwork群组") {
        this.isGroupDialog = true;
      }
      if (name === "渠道视图") {
        this.$refs.storeDialog.init(name, this.id, this.menDianTreeData);
      }
      this.handleActIsShow();
    },
    // 选择标签
    handLableId() {
      let con = this.lableVal.split(",");
      this.form.lableName = con[0];
      this.form.lableId = con[1];
      this.relaryLableName = con[0];
      this.isLableDialog = false;
      this.fetchAgainGroupData(con[1]);
    },
    //格式化小数点
    handleInput(value) {
      if (value != "") {
        if (value.indexOf(".") > -1) {
          this.recoveryAmount = value.substring(0, value.indexOf("."));
        } else {
          this.recoveryAmount = value;
        }
        // this.form.calledNum=this.recoveryAmount
      }
    },
    handleInput2(value) {
      console.log("-----", value);
      if (value != "") {
        if (value.indexOf(".") > -1) {
          this.form.threshold = value.substring(0, value.indexOf("."));
        } else {
          this.form.threshold = value;
        }
        // this.form.calledNum=this.recoveryAmount
      }
      console.log("===========", this.form.threshold);
    },
    fetchLableList() {
      this.$http({
        url: this.$http.adornUrl("sysdictdata/list"),
        method: "get",
        params: this.$http.adornParams({
          dictType: "du_user_tag",
        }),
      }).then(({ data }) => {
        if (data && data.code === 0) {
          this.lableList = data.page.list;
        }
      });
    },
    changeTitleCon() {
      // this.pushTimeType = 1
      // const titleOrContent = this.form.titleval.split(",");
      // //选择异动预警-疑似异网营销的时候，推送周期只显示'日'
      // if (titleOrContent[0] === "异动预警-疑似异网营销") {
      //   let object = this.cycleList.find((item) => {
      //     return item.dictName === "日";
      //   });
      //   console.log(object);
      //   this.cycleList = [];
      //   this.cycleList.push(object);
      //   console.log("-----", this.cycleList);
      // } else {
      //   console.log("123456");
      //   this.fetchCycleData();
      // }
      // console.log("titleOrContent", titleOrContent);
      // (this.form.sendUnitType = ""), //每次切换推送场景，sendUnitType为空，这个值来判断升级条件等的显隐
      //   (this.form.whether = "2"); //每次选取推送场景时候，让这个值=2，目的是，对应的场景显示出推送对象，当选择自定义文本推送时候，是否升级对象显示为否，推送对象上传和导出功能隐藏
      // this.form.unitType = ""; //每次选取推送场景时候，这个值来判断选取的推送层级，每次都默认不选择
      // this.form.titleName = titleOrContent[0];
      // this.form.desc = titleOrContent[1];
      // this.isActShow = false;
      // this.form.actSecenVal = "";
      // this.isObjectShow = false;
      // this.whetherShow = false;
      // this.upgradeShow = false;
      // this.isTreeShow = false;
      // this.isTextShow = false;
      // this.contentShow = false;
      // this.imageShow = true;
      // this.imageShengShow = true;
      // this.pushlevelShow = false;
      // this.tinymceisImgShow = true;
      // switch (titleOrContent[0]) {
      //   case "活动上线":
      //     this.form.checkedCities = `hdsx,盯${titleOrContent[0]}`;
      //     this.isActShow = true;
      //     break;
      //   case "活动执行":
      //     this.form.checkedCities = `hdzx,盯${titleOrContent[0]}`;
      //     break;
      //   case "活动转换":
      //     this.form.checkedCities = `hdzh,盯${titleOrContent[0]}`;
      //     break;
      //   case "快电数字化":
      //     this.form.checkedCities = `kd_szh,盯${titleOrContent[0]}`;
      //     break;
      //   case "自定义文本推送":
      //     this.form.checkedCities = `cswbts,盯${titleOrContent[0]}`;
      //     this.isTreeShow = true;
      //     this.isObjectShow = true;
      //     this.tinymceisImgShow = false;
      //     this.contentShow = true;
      //     this.whetherShow = true;
      //     console.log("-222222222222222222", this.cycleList);
      //     break;
      //   case "“一站一营销”5G精准提升":
      //     this.form.checkedCities = `5G_yzyyx,盯${titleOrContent[0]}`;
      //     // this.isActShow = true
      //     // this.isObjectShow = true
      //     break;
      //   case "5G运营十大场景攻坚-换机":
      //     this.form.checkedCities = `5G_hj,盯${titleOrContent[0]}`;
      //     // this.isActShow = true
      //     this.isObjectShow = true;
      //     break;
      //   case "活动拆分":
      //     this.form.checkedCities = `hdcf,盯${titleOrContent[0]}`;
      //     // this.isActShow = true;
      //     this.isObjectShow = true;
      //     break;
      //   case "大融合-极致融合":
      //     this.form.checkedCities = `drh_jzrh,盯${titleOrContent[0]}`;
      //     break;
      //   case "个性化触发场景":
      //     this.form.checkedCities = `gxh_scene,盯${titleOrContent[0]}`;
      //     this.isTreeShow = true;
      //     this.isTextShow = true;
      //     this.isObjectShow = true;
      //     break;
      //   case "异动预警-疑似异网营销":
      //     this.form.checkedCities = `ydyj,盯${titleOrContent[0]}`;
      //     this.pushlevelShow = true;
      //     this.userType = "6";
      //     break;
      // }
      // if (
      //   this.form.checkedCities.split(",")[0] === "kd_szh" ||
      //   this.form.checkedCities.split(",")[0] === "gxh_scene"
      // ) {
      //   this.form.calledNum = 5;
      // }
      // if (this.form.checkedCities.split(",")[0] === "ydyj") {
      //   this.latnId = this.cityCode;
      // } else {
      //   this.latnId = "";
      // }
    },
    //点击推送层级
    changeUnitType() {
      console.log("this.form.sendUnitType", this.form.sendUnitType);
      console.log("this.form.sendUnitType", typeof this.form.sendUnitType);
      if (this.form.sendUnitType === null) {
        this.form.unitType = "";
      } else {
        this.form.unitType = this.form.sendUnitType;
      }

      // this.getVariable();
      console.log(this.form.unitType);
      this.form.isUpgrade = "0"; //是否升级对象 0：否，1：是
      this.form.filterType = ""; //升级条件
      this.form.filterCondit = ""; //触发条件
      this.form.desc = ""; //推送内容（插入变量）
      // console.log("this.form.sendUnitType===",this.form.sendUnitType);
      if (this.form.sendUnitType === "4" || this.form.sendUnitType === "5") {
        this.upgradeShow = true;
      } else {
        this.upgradeShow = false;
      }
      // if (this.form.sendUnitType === "2" || this.form.sendUnitType === "3") {
      //   this.form.threshold = "";
      // } else {
      //   this.form.threshold = "5";
      // }
      console.log("是否向上升级", this.form.isUpgrade);
      console.log("是否向上升级", typeof this.form.isUpgrade);

      if (this.form.isUpgrade === "0") {
        console.log("11111");
        this.form.threshold = "";
      } else {
        console.log("2222");
        this.form.threshold = "5";
      }
      console.log("----", this.form.threshold);
      // console.log("24534534634", this.form.threshold);
      // console.log("24534534634", this.form.isUpgrade);
    },
    //点击是否向上升级
    changeRadio(value) {
      // console.log("1111",value);
      // console.log("1111",typeof value);
      if (value === "" || value === "0") {
        this.form.threshold = "";
      } else {
        this.form.threshold = "5";
      }
      console.log("----this.form.threshold=", this.form.threshold);
    },
    //判断推送内容禁止状态
    getDisabled(isTrue) {
      // let flag = isTrue;
      // // console.log("flag===", flag);
      // if (
      //   this.form.checkedCities.split(",")[0] === "cswbts" ||
      //   this.form.checkedCities.split(",")[0] === "gxh_scene" ||
      //   this.form.checkedCities.split(",")[0] === "ydyj"
      // ) {
      //   flag = false;
      // } else {
      //   flag = true;
      // }
      // return flag;
    },
    handleChangeGroupId() {
      let con = this.groupIdVal.split(",");
      this.form.groupId = con[1];
      this.form.groupName = con[0];
      this.relaryGroupName = con[0];
      this.isGroupDialog = false;
    },
    //  获取群组列表
    fetchGroupList() {
      this.$http({
        url: this.$http.adornUrl("sysdictdata/listByUser"),
        method: "get",
        params: this.$http.adornParams({
          page: 1,
          limit: 1000,
        }),
      }).then(({ data }) => {
        if (data && data.code === 0) {
          this.groupList = data.page.list;
        }
      });
    },
    //  字典获取值
    fetchTitleList() {
      this.$http({
        url: this.$http.adornUrl("/sysdictdata/list"),
        method: "get",
        params: this.$http.adornParams({
          dictType: "du_text",
        }),
      }).then(({ data }) => {
        if (data && data.code === 0) {
          console.log("data.page.list===", data.page.list);
          // let object = this.cycleList.find((item) => {
          //   return item.dictName === "日";
          // });
          // this.titleList = data.page.list;
          let object = data.page.list.find((item) => {
            return (item.dictName = "异动预警-疑似异网营销");
          });
          this.titleList = [];
          this.titleList.push(object);
          console.log("-----", this.titleList);
          this.pushlevelShow = true;
          this.contentShow = false;
          this.userType = "6";
          // console.log("this.cityCode====", this.cityCode);
          // this.latnId = this.cityCode;
          this.titleList.forEach((element) => {
            console.log(
              "_-----------",
              element.dictName + "element.remark===" + element.remark
            );
            this.form.titleval = element.dictName + element.remark;
            this.form.titleName = element.dictName;
          });
        }
      });
      this.fetchCycleData();
    },
    // 弹框直接推送
    handleNowpush(id) {
      let ids = [id];
      this.$http({
        url: this.$http.adornUrl("/cpcpdu/sendOneMessage"),
        method: "post",
        data: this.$http.adornData(ids, false),
      }).then(({ data }) => {
        if (data && data.code === 0) {
          this.$message({
            message: "推送成功",
            type: "success",
          });
          this.fetchTableList();
        } else {
          console.log("qqqqqqqqqqqqqqqqqqqqqqqqqqq");
          this.$message.error(data.msg);
        }
      });
    },
    // 确定推送
    handlePushPerson(id) {
      let ids = [id];
      this.$confirm(`您确定要推送吗`, "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          this.$http({
            url: this.$http.adornUrl("/cpcpdu/sendOneMessage"),
            method: "post",
            data: this.$http.adornData(ids, false),
          }).then(({ data }) => {
            if (data && data.code === 0) {
              this.$message({
                message: "推送成功",
                type: "success",
              });
              this.fetchTableList();
            } else {
              console.log("1111111111");
              this.$message.error(data.msg);
            }
          });
        })
        .catch(() => {});
    },
    //  获取子组件人员id
    fetchPersonId(params) {
      let r_staffId = [];
      let q_orgId = [];
      let r_staffAccount = [];
      let q_staffAccount = [];
      let r_staffName = [];
      let q_staffName = [];
      if (params[0]) {
        params[0].map((item) => {
          r_staffId.push(item.staffId);
          r_staffAccount.push(item.staffAccount);
          r_staffName.push(item.staffName);
        });
      }
      if (params[1]) {
        params[1].map((item) => {
          q_orgId.push(item.orgId);
          q_staffAccount.push(item.orgId);
          q_staffName.push(item.orgName);
        });
      }
      this.sendStaffAccount = r_staffAccount.toString() + "#" + q_staffAccount;
      this.form.groupId = r_staffId.toString() + "#" + q_orgId.toString();
      this.personList = [...r_staffName, ...q_staffName].toString();
      // if (val.length > 0) {
      //   let list = [];
      //   let person = [];
      //   let sendStaffAccount = []
      //   val.map((item) => {
      //     list.push(item.staffId);
      //     person.push(item.staffName);
      //     sendStaffAccount.push(item.staffAccount)
      //   });
      //   this.sendStaffAccount = sendStaffAccount.toString();
      //   this.form.groupId = list.toString();
      //   this.personList = person.toString();
      // } else {
      //   this.personList = "";
      // }
    },
    handleActIsShow(val) {
      if (!val) {
        this.form.groupId = null;
        this.selectTreeData.ssCode = null;
        this.sendStaffAccount = "";
        this.form.groupName = "";
        this.relaryGroupName = "";
        this.form.lableName = "";
        this.form.lableId = "";
        this.lableVal = "";
        this.relaryLableName = "";
        this.personList = "";
        this.groupIdVal = "";
      }
      if (
        this.changeName === "选择主数据人员" ||
        this.changeName === "监控门店类型"
      ) {
        this.isRealy = true;
        this.isPerson = false;
        this.isIwork = false;
      }
      if (this.changeName === "选择主数据群组") {
        this.isPerson = true;
        this.isIwork = false;
        this.isRealy = true;
      }
      if (this.changeName === "选择Iwork群组") {
        this.isPerson = false;
        this.isIwork = true;
        this.isRealy = false;
      }
    },
    handleResetAct() {
      if (this.form.pattern == 0) {
      } else {
        this.form.imgOrTextVal = 1;
        this.isImgShow = false;
        this.contentShow = false;
        // this.tinymceisImgShow = false;
        this.form.checkedCities = "";
      }
    },
    //  点击详情
    handleDetail(id) {
      this.$router.push({
        path: "/duDetails",
        query: {
          id,
        },
      });
    },
    //城市
    getIWorkCity(item) {
      let str = "";
      str += item.cityName;
      str += "</br>" + item.cityId + "";
      return str;
    },
    //推送人
    getIWorkState(item) {
      let str = "";

      // if (item.staffName) {
      // str += "item.staffAccount";
      str += item.staffAccount;
      str += "</br>" + item.staffName + "";
      // str = item.staffAccount + '&nbsp;&nbsp;'+"/" +'&nbsp;&nbsp;' + item.staffName ;
      // }

      return str;
    },
    //  选择推送对象
    handleChangeGroup() {
      if (this.form.pattern == 1) {
        this.isGroupDialog = true;
      } else {
        this.$refs.send.init("选择主数据人员", this.id, this.form.groupId);
      }
    },
    handleChangeImgOrText() {
      this.isActShow = false;
      this.isObjectShow = false;
      this.isTreeShow = false;
      this.isTextShow = false;
      this.whetherShow = false;
      // 是图片还是文本
      if (this.form.imgOrTextVal == 0) {
        this.isImgShow = true;
        this.contentShow = true;
        this.tinymceisImgShow = true;
        // 是图片的时候， 是活动拆分和活动上线的时候
        if (
          (this.form.checkedCities &&
            this.form.checkedCities.split(",")[0] === "hdcf") ||
          this.form.checkedCities.split(",")[0] === "hdsx"
        ) {
          this.isActShow = true;
        }
        // 是图片的时候，是活动上线的时候
        if (
          this.form.checkedCities &&
          this.form.checkedCities.split(",")[0] === "hdcf"
        ) {
          this.isObjectShow = true;
        } else {
          this.isObjectShow = false;
        }
      } else {
        this.isImgShow = false;
        this.contentShow = false;
        // this.tinymceisImgShow = false;
        // 是文本的时候， 是活动拆分和活动上线的时候
        if (
          (this.form.titleval &&
            this.form.titleval.split(",")[0] === "活动拆分") ||
          this.form.titleval.split(",")[0] === "活动上线"
        ) {
          this.isActShow = true;
        }
        // 是文本的时候，是活动上线的时候
        if (
          (this.form.titleval &&
            this.form.titleval.split(",")[0] === "活动拆分") ||
          this.form.titleval.split(",")[0] === "个性化触发场景"
        ) {
          this.isObjectShow = true;
        } else {
          this.isObjectShow = false;
        }
        // 是文本的时候，是分公司个性化场景的时候
        if (this.form.titleval.split(",")[0] === "个性化触发场景") {
          this.isTreeShow = true;
          this.isTextShow = true;
        }
        if (this.form.titleval.split(",")[0] === "自定义文本推送") {
          this.isTreeShow = true;
        }
      }
    },
    //  切换推送方式
    handleChangepushType() {
      this.pushTimeType === 0 ? (this.isCycle = true) : (this.isCycle = false);
    },
    //点击取消
    close() {
      this.dialogVisible = false;
      this.form.calledNum = 5;
      this.form.dabiaoNum = 5;
      this.selectTreeData.ssName = "";
      this.selectTreeData.ssCode = "";
      this.selectTreeData.actId = "";
      this.selectTreeData.actName = "";
      this.uploadForm.upgradeNames = "";
      this.shengjiList = "";
      this.personList = "";
      this.form.whether = "2";
    },
    //弹出层右上角关闭
    closeDialog() {
      this.form.calledNum = 5;
      this.form.dabiaoNum = 5;
      this.selectTreeData.ssName = "";
      this.selectTreeData.ssCode = "";
      this.selectTreeData.actId = "";
      this.selectTreeData.actName = "";
      this.uploadForm.upgradeNames = "";
      this.shengjiList = "";
      this.personList = "";
      this.form.whether = "2";
    },
    // 保存
    handleSave() {
      console.log("新增编辑页面保存");
      if (this.id) {
        this.handleUpdateDic();
      } else {
        this.handleAddDic();
      }
    },
    // 获取推送图片的url
    getImgUrls() {
      let imgUrls = [];
      if (this.form.titleval.split(",")[0] === "自定义文本推送") {
        this.fileList.map((item) => {
          imgUrls.push(item.url);
        });
      }
      return imgUrls.toString();
    },
    // 获取推送附件的url
    getEnclosureUrls() {
      let enclosureUrls = [];
      if (this.form.titleval.split(",")[0] === "自定义文本推送") {
        this.fileListFile.map((item) => {
          console.log("itemitemitemitem",item.url);
          enclosureUrls.push(item.url);
        });
      }
      return enclosureUrls.toString();
    },
    // 新增
    handleAddDic() {
      console.log("-------------", this.form.whether);
      this.getTime();
      // console.log(this.form);
      console.log("选取推送场景---------------", this.form.titleval);
      console.log("选取推送场景---------------", typeof this.form.titleval);
      console.log("选取推送标题---------------", this.form.titleName);
      console.log("选取推送标题---------------", typeof this.form.titleName);

      console.log("选取推送层级", this.form.sendUnitType);
      console.log("----------", typeof this.form.sendUnitType);
      // console.log("----------",typeof parseInt(this.form.sendUnitType));
      console.log("是否向上升级", this.form.isUpgrade);
      console.log("isUpgrade", typeof parseInt(this.form.isUpgrade));
      console.log("升级条件", this.form.filterType);
      console.log("升级条件", typeof parseInt(this.form.filterType));
      console.log("触发条件", this.form.filterCondit);
      console.log("触发条件", typeof parseInt(this.form.filterCondit));
      console.log("阈值", this.form.threshold / 100);
      console.log("阈值", typeof (this.form.threshold + ""));

      console.log("this.userType===", this.userType);
      console.log("this----------", this.latnId);
      console.log("推送方式", this.form.mode);
      console.log("推送方式", typeof this.form.mode);
      console.log("推送周期", this.cycle);
      console.log("推送周期", typeof this.cycle);
      if (this.form.upgradeTitle === "") {
        this.form.upgradeTitle = "升级标题";
      }
      if (this.form.upgradeContent === "") {
        this.form.upgradeContent = "升级内容";
      }
      if (this.form.isUpgrade === "0") {
        this.form.upgradeTitle = "";
        this.form.upgradeContent = "";
      }
      console.log("du升级人员标题", this.form.upgradeTitle);
      console.log("du升级人员标题", typeof this.form.upgradeTitle);
      console.log("du升级人员内容", this.form.upgradeContent);
      console.log("du升级人员内容", typeof this.form.upgradeContent);
      console.log("apiKey=====", this.apiKey);
      console.log("staffAccountToken====", this.staffAccountToken);
      console.log("token====", this.$cookie.get("token"));
      console.log("latnId====", this.latnId);
      // alert("功能开发中.......");
      if (this.form.titleval === "" || this.form.titleval === null) {
        this.$message.error("请填写推送场景");
        return;
      }
      console.log("选取推送场景---------------", this.form.titleval);
      console.log("选取推送场景---------------", typeof this.form.titleval);
      if (this.form.titleName === "" || this.form.titleName === null) {
        this.$message.error("请填写推送标题");
        return;
      }
      console.log("选取推送标题---------------", this.form.titleName);
      console.log("选取推送标题---------------", typeof this.form.titleName);
      if (this.form.sendUnitType === "" || this.form.sendUnitType === null) {
        this.$message.error("请选取推送层级");
        return;
      }
      if (this.form.desc === "" || this.form.desc === null) {
        this.$message.error("请填写推送内容");
        return;
      }
      console.log("取推送层级====", this.form.sendUnitType);
      if (this.form.isUpgrade === "1") {
        console.log("---------------------------------------------");
        if (this.form.filterType === "") {
          this.$message.error("请选择升级条件");
          return;
        }
        console.log("请选择升级条件-------");
        if (this.form.filterCondit === "") {
          this.$message.error("请选择触发条件");
          return;
        }
        console.log("请选择触发条件-------");
        if (
          this.form.threshold === "" ||
          this.form.threshold === NaN ||
          this.form.threshold === undefined
        ) {
          this.$message.error("请填写阈值");
          return;
        }
        console.log("阈值-------", this.form.threshold);
        console.log("阈值-------", typeof this.form.threshold);
      } else {
        console.log("升级条件-------", this.form.filterType);
        console.log("升级条件-------", typeof this.form.filterType);
        console.log("触发条件-------", this.form.filterCondit);
        console.log("触发条件-------", typeof this.form.filterCondit);
        console.log("阈值-------", this.form.threshold / 100);
        console.log("阈值-------", typeof this.form.threshold / 100);
      }
      // return;
      if (this.selectTreeData.actId === "undefined")
        this.selectTreeData.actId = "";
      if (this.selectTreeData.ssCode === "undefined")
        this.selectTreeData.ssCode = "";
      let activity =
        this.form.checkedCities != "" ? this.form.checkedCities.split(",") : "";
      let leble = this.lableVal != "" ? this.lableVal.split(",") : "";
      this.$http({
        url: this.$http.adornUrl("/cpcpdu/save"),
        method: "post",
        data: this.$http.adornData({
          content: this.form.desc,
          sendType: this.form.mode, //推送方式
          sendTime: this.form.timeVal ? this.form.timeVal + ":00" : "",
          sendTimeType: this.cycle,
          sendGroup: this.form.pattern, //推送模式  0个人 1群组
          groupName: this.form.groupName,
          groupId: this.form.groupId,
          labelId: leble[1], // 主数据群组回显
          labelName: leble[0], // 主数据群组回显
          pattern: this.form.imgOrTextVal,
          // activityId: activity[0], //之前下拉框选择出来的字段名
          // activityName: activity[1],//之前下拉框选择出来的字段值
          activityId: "ydyj",
          activityName: "盯异动预警-疑似异网营销",
          title: this.form.titleName,
          isTiming: this.pushTimeType,
          activitySplitId: this.form.actSecenVal,
          calledNum: this.form.calledNum || "",
          storyStaffAccounts: this.selectTreeData.ssCode, //门店类型下的员工 逗号分割
          // isAllStaff: this.isChecked, //是否全选 1是0否
          isAllCampaign: this.isAllCampaign, //是否全选 1是0否
          campaignIds: this.selectTreeData.actId, //活动类型Id 逗号分割 最多4个
          // calledNum: this.form.dabiaoNum, //（达标标准）
          triggerType: this.dictValue, //触发类型
          userType: this.userType,
          sendStaffAccounts: this.sendStaffAccount,
          imgUrls: this.getImgUrls(), // 获取图片数据
          fileUrls: this.getEnclosureUrls(), // 获取推送附件数据
          // 新加字段
          sendUnitType: parseInt(this.form.sendUnitType), //选取推送层级
          isUpgrade: parseInt(this.form.isUpgrade), //是否升级 0 否 1 是
          filterType: parseInt(this.form.filterType), //升级条件
          filterCondit: parseInt(this.form.filterCondit), //触发条件
          threshold: this.form.threshold + "", //阈值
          upgradeTitle: this.form.upgradeTitle, //du升级人员标题
          upgradeContent: this.form.upgradeContent, //du升级人员内容
          latnId: this.latnId, //当前登录人的地市code
          //第三方调用的字段
          apiKey: this.apiKey,
          token: this.$cookie.get("token"),
          isTripartite: 1,
        }),
      }).then(({ data }) => {
        if (data && data.code === 0) {
          this.$message({
            message: "添加成功",
            type: "success",
          });
          this.handleNowpush(data.duId)
          // this.getImmediately()
          this.dialogVisible = false;
          this.fetchTableList();
          this.uploadForm.upgradeNames = "";
          this.shengjiList = "";
          this.personList = "";
          this.form.whether = "2";
        } else {
          this.$message.error(data.msg);
        }
      });
    },
    //立即推送
    getImmediately() {
      // return
      if (this.pushTimeType == 1) {
        // this.$confirm(`您确定立即推送吗`, "提示", {
        //   confirmButtonText: "确定",
        //   cancelButtonText: "取消",
        //   type: "warning",
        // })
        //   .then(() => {
            this.handleNowpush(data.duId);
            this.dialogVisible = false;
      //     })
      //     .catch(() => {
      //       this.dialogVisible = false;
      //     });
      }
    },
    //获取当前时间（时分秒）
    getTime() {
      // var myDate = new Date();
      var date = new Date();
      var year = date.getFullYear();
      var month = date.getMonth() + 1;
      var day = date.getDate();
      let h = date.getHours();
      h = h < 10 ? "0" + h : h;
      let m = date.getMinutes();
      m = m < 10 ? "0" + m : m;
      let s = date.getSeconds();
      s = s < 10 ? "0" + s : s;
      month = month < 10 ? "0" + month : month;
      day = day < 10 ? "0" + day : day;
      let str = "";
      // str = year + "-" + month + "-" + day + " " + h + ":" + m + ":" + s
      str = h + ":" + m + ":" + s;
      console.log("strstr", str);
      // let str2 = ""
      return str;
    },
    insertWaihuLog(id) {
      this.$http({
        url: this.$http.adornUrl("/cpcplog/insertLog"),
        method: "post",
        params: this.$http.adornParams({
          id: id,
        }),
      }).then((res) => {
        if (res.data.code === 0) {
          this.$message({
            message: "调用成功",
            type: "success",
          });
          this.fetchTableList();
          this.dialogVisible = false;
        } else {
          console.log("3333333333333333");
          this.$message({
            showClose: true,
            message: data.msg,
            type: "error",
          });
        }
      });
    },
    // 修改
    handleUpdateDic() {
      console.log("this.isYdWarn", this.isYdWarn);
      console.log("this.id", this.id);
      console.log("this.ydExpandId", this.ydExpandId);
      // return
      if (this.isYdWarn === 0) {
        let activity =
          this.form.checkedCities != ""
            ? this.form.checkedCities.split(",")
            : "";
        let leble = this.lableVal != "" ? this.lableVal.split(",") : "";
        // return
        this.$http({
          url: this.$http.adornUrl("/cpcpdu/update"),
          method: "post",
          data: this.$http.adornData({
            id: this.id,
            serviceType: "du_service",
            content: this.form.desc,
            sendType: this.form.mode, //推送方式
            sendTime: this.form.timeVal ? this.form.timeVal + ":00" : "",
            sendTimeType: this.cycle,
            sendGroup: this.form.pattern, //推送模式
            groupName: this.form.groupName,
            groupId: this.form.groupId,
            labelId: leble[1],
            labelName: leble[0],
            pattern: this.form.imgOrTextVal,
            activityId: activity[0],
            activityName: activity[1],
            title: this.form.titleName,
            isTiming: this.pushTimeType,
            activitySplitId: this.form.actSecenVal,
            calledNum: this.form.calledNum || "",
            storyStaffAccounts: this.selectTreeData.ssCode, //门店类型下的员工 逗号分割
            // isAllStaff: this.isChecked, //是否全选 1是0否
            isAllCampaign: this.isAllCampaign, //是否全选 1是0否
            campaignIds: this.selectTreeData.actId, //活动类型Id 逗号分割 最多4个
            // calledNum: this.form.dabiaoNum, //（达标标准）
            triggerType: this.dictValue, //触发类型
            userType: this.userType,
            sendStaffAccounts: this.sendStaffAccount,
            imgUrls: this.getImgUrls(), // 获取图片数据
            fileUrls: this.getEnclosureUrls(), // 获取推送附件数据
          }),
        }).then(({ data }) => {
          if (data && data.code === 0) {
            this.$message({
              message: "更新成功",
              type: "success",
            });
            if (this.pushTimeType == 1) {
              this.$confirm(`您确定立即推送吗`, "提示", {
                confirmButtonText: "确定",
                cancelButtonText: "取消",
                type: "warning",
              })
                .then(() => {
                  this.handleNowpush(this.id);
                  this.dialogVisible = false;
                })
                .catch(() => {
                  this.dialogVisible = false;
                });
            }
            this.dialogVisible = false;
            this.fetchTableList();
            this.uploadForm.upgradeNames = "";
            this.shengjiList = "";
            this.personList = "";
            this.form.whether = "2";
          } else {
            console.log("555555555555555");
            this.$message({
              showClose: true,
              message: data.msg,
              type: "error",
            });
          }
        });
      } else {
        let activity =
          this.form.checkedCities != ""
            ? this.form.checkedCities.split(",")
            : "";
        let leble = this.lableVal != "" ? this.lableVal.split(",") : "";
        // return
        this.$http({
          url: this.$http.adornUrl("/ydExpand/updateYdScene"),
          method: "post",
          data: this.$http.adornData({
            duId: this.id,
            ydExpandId: this.ydExpandId,
            serviceType: "du_service",
            content: this.form.desc,
            sendType: this.form.mode, //推送方式
            sendTime: this.form.timeVal ? this.form.timeVal + ":00" : "",
            sendTimeType: this.cycle,
            sendGroup: this.form.pattern, //推送模式
            groupName: this.form.groupName,
            groupId: this.form.groupId,
            labelId: leble[1],
            labelName: leble[0],
            pattern: this.form.imgOrTextVal,
            activityId: activity[0],
            activityName: activity[1],
            title: this.form.titleName,
            isTiming: this.pushTimeType,
            activitySplitId: this.form.actSecenVal,
            calledNum: this.form.calledNum || "",
            storyStaffAccounts: this.selectTreeData.ssCode, //门店类型下的员工 逗号分割
            // isAllStaff: this.isChecked, //是否全选 1是0否
            isAllCampaign: this.isAllCampaign, //是否全选 1是0否
            campaignIds: this.selectTreeData.actId, //活动类型Id 逗号分割 最多4个
            // calledNum: this.form.dabiaoNum, //（达标标准）
            triggerType: this.dictValue, //触发类型
            userType: this.userType,
            sendStaffAccounts: this.sendStaffAccount,
            imgUrls: this.getImgUrls(), // 获取图片数据
            fileUrls: this.getEnclosureUrls(), // 获取推送附件数据
            // 新加字段
            sendUnitType: parseInt(this.form.sendUnitType), //选取推送层级
            isUpgrade: parseInt(this.form.isUpgrade), //是否升级 0 否 1 是
            filterType: parseInt(this.form.filterType), //升级条件
            filterCondit: parseInt(this.form.filterCondit), //触发条件
            threshold: this.form.threshold + "", //阈值
            upgradeTitle: this.form.upgradeTitle, //du升级人员标题
            upgradeContent: this.form.upgradeContent, //du升级人员内容
          }),
        }).then(({ data }) => {
          if (data && data.code === 0) {
            this.$message({
              message: "更新成功",
              type: "success",
            });
            if (this.pushTimeType == 1) {
              this.$confirm(`您确定立即推送吗`, "提示", {
                confirmButtonText: "确定",
                cancelButtonText: "取消",
                type: "warning",
              })
                .then(() => {
                  this.handleNowpush(this.id);
                  this.dialogVisible = false;
                })
                .catch(() => {
                  this.dialogVisible = false;
                });
            }
            this.dialogVisible = false;
            this.fetchTableList();
            this.uploadForm.upgradeNames = "";
            this.shengjiList = "";
            this.personList = "";
            this.form.whether = "2";
          } else {
            console.log("555555555555555");
            this.$message({
              showClose: true,
              message: data.msg,
              type: "error",
            });
          }
        });
      }
    },
    // 推送
    handlePush() {},
    //   新增
    handleAdd() {
      // console.log("哈哈哈");
      this.dialogVisible = true;
      this.imageShow = true;
      // this.fetchTitleList()
      this.imageShengShow = true;
      this.isAllCampaign = null;
      (this.id = null), (this.form.mode = "0");
      this.form.pattern = "0";
      // this.pushTimeType = 0;
      this.pushTimeType = 1; //推送时间现在改为立即推送
      this.form.imgOrTextVal = 1;
      this.form.timeVal = "";
      this.form.checkedCities = "";
      this.form.desc = "";
      this.form.titleName = "";
      this.personList = "";
      this.form.actSecenVal = "";
      this.form.titleval = "";
      this.actVal = "";
      this.form.checkedCitiesNum = "";
      this.handleChangeImgOrText();
      this.handleActIsShow();
      this.selectTreeData.ssName = "";
      this.selectTreeData.ssCode = "";
      this.selectTreeData.actId = "";
      this.selectTreeData.actName = "";
      this.treeHuongDongData = [];
      this.menDianTreeData = "";
      this.fileList = [];
      this.contentShow = true;
      this.tinymceisImgShow = true;
      this.form.sendUnitType = ""; //选取推送层级
      this.pushlevelShow = false; //选取推送层级隐藏
      this.form.isUpgrade = "0"; //是否升级 0 否 1 是
      this.upgradeShow = false; //是否升级隐藏
      this.form.filterType = ""; //升级条件
      this.form.filterCondit = ""; //触发条件
      this.form.threshold = "5"; //阈值
      this.form.upgradeTitle = ""; //du升级人员标题
      this.form.upgradeContent = ""; //du升级人员内容
      this.form.unitType = ""; //点击插入变量时候传的参数
      // sendUnitType: parseInt(this.form.sendUnitType), //选取推送层级
      //     isUpgrade: parseInt(this.form.isUpgrade), //是否升级 0 否 1 是
      //     filterType: parseInt(this.form.filterType), //升级条件
      //     filterCondit: parseInt(this.form.filterCondit), //触发条件
      //     threshold: (this.form.threshold + ""), //阈值
      //     upgradeTitle: this.form.upgradeTitle, //du升级人员标题
      //     upgradeContent: this.form.upgradeContent, //du升级人员内容
    },
    // 多选
    handleSelectionChange(val) {
      this.ids = [];
      val.map((item) => {
        this.ids.push(item.id);
      });
    },
    // 点击搜索
    searchData() {
      this.fetchTableList();
    },
    // 获取表格数据
    fetchTableList() {
      const {
        sendType,
        masterValue,
        iworkValue,
        numVaue,
        nameValue,
        secenValue,
        isOnlyScene,
        staffValue,
      } = this.dataForm;
      this.$http({
        url: this.$http.adornUrl("cpcpdu/list"),
        method: "get",
        params: this.$http.adornParams({
          page: this.pageNum,
          limit: this.pageSize,
          send_type: sendType,
          // jobNoLike: numVaue,
          // userName: nameValue,
          activity_id: secenValue,
          label_id: masterValue,
          group_id: iworkValue,
          isOnlyScene: isOnlyScene,
          staffValue: staffValue,
        }),
      }).then(({ data }) => {
        if (data && data.code === 0) {
          this.total = data.page.totalCount;
          this.dataList = data.page.list;
        }
      });
    },
    //编辑
    handleEdit(id) {
      this.id = id;
      this.$http({
        url: this.$http.adornUrl(`/cpcpdu/info/${id}`),
        method: "get",
        params: this.$http.adornParams({}),
      }).then((res) => {
        if (res.data.code === 0) {
          this.dialogVisible = true;
          let data = res.data.cpcpDu;
          console.log("---------------", data);
          this.form.desc = data.content;
          this.form.mode = data.sendType.toString();
          this.form.timeVal = data.sendTime.slice(0, 5);
          this.form.pattern = data.sendGroup.toString();
          this.form.checkedCities = `${data.activityId},${data.activityName}`;
          this.actVal = data.activityName;
          this.form.titleName = data.title;
          this.pushTimeType = data.isTiming;
          this.form.groupId = data.groupId;
          // this.form.whether = data.whether //暂时没这个字段
          this.form.whether = "2"; //暂时没这个字段
          this.relaryGroupName = data.groupName;
          this.lableVal = data.labelId
            ? `${data.labelName},${data.labelId}`
            : "";
          this.relaryLableName = data.labelName;
          this.form.imgOrTextVal = data.pattern;
          this.form.titleval = data.title + "," + data.content;
          // 自定义文本推送 , 分公司个性化场景, select, name ,content 回显
          // if (data.activityId === "gxh_scene" || data.activityId === "cswbts") {
          //   this.form.titleval = data.title + "," + data.originalContent;
          //   this.titleList.map(item => {
          //     if(item.dictName === "自定义文本推送"){
          //       this.form.titleval = item.dictName + "," + item.remark;
          //     }
          //   })
          // }
          if (data.activityId === "gxh_scene") {
            this.form.titleval = data.title + "," + data.originalContent;
          }
          if (data.activityId === "ydyj") {
            this.form.titleval = data.title + "," + data.originalContent;
          }
          //自定义文本推送 修改成了富文本编辑器，编辑的时候titleval回显有问题，从新获取内容
          if (data.activityId === "cswbts") {
            // console.log("1111111111111111111111111111");

            console.log("this.whetherShow===", this.whetherShow);
            this.titleList.map((item) => {
              if (item.dictName === "自定义文本推送") {
                this.form.titleval = item.dictName + "," + item.remark;
              }
            });
            // 回显图片
            this.fileList = [];
            let imgStr = data.imgUrls.split(",");
            imgStr.map((item) => {
              let obj = {};
              obj.url = item;
              this.fileList.push(obj);
            });
          }
          //新回显的字段（异动预警）
          // this.form.sendUnitType = data.sendUnitType; //选取推送层级
          // this.pushlevelShow = true; //选取推送层级隐藏
          // this.form.isUpgrade = "0"; //是否升级 0 否 1 是
          // this.upgradeShow = false; //是否升级隐藏
          // this.form.filterType = ""; //升级条件
          // this.form.filterCondit = ""; //触发条件
          // this.form.threshold = "5"; //阈值
          // this.form.upgradeTitle = ""; //du升级人员标题
          // this.form.upgradeContent = ""; //du升级人员内容

          // this.form.actSecenVal = data.activitySplitId;
          // 判断 所有活动，还是 若干个活动  0 -> 若干活动  1-> 所有活动
          this.treeHuongDongData = [];
          this.isAllCampaign = data.isAllCampaign;
          if (data.isAllCampaign == 0) {
            let list = data.cpcpActivityList ? data.cpcpActivityList : []; //活动类型Id 逗号分割 最多4个
            let Actid = "";
            if (list) {
              list.map((item) => {
                this.treeHuongDongData.push(item);
                this.selectTreeData.actName += item.actName + ",";
                Actid += item.actId + ",";
                this.selectTreeData.actId = Actid.substring(
                  0,
                  Actid.length - 1
                );
              });
            }
          } else {
            this.selectTreeData.actName = "所有活动";
          }
          if (data.storyStaffAccounts) {
            this.menDianTreeData = data.storyStaffAccounts;
            this.$refs.storeDialog.fetchAgainData(this.menDianTreeData);
          }
          this.dictValue = data.triggerType.toString(); //触发类型
          this.form.calledNum = data.calledNum; //达标条件
          if (data.activityId === "hdcf" || data.activityId === "hdsx") {
            this.isActShow = true;
          }
          this.handleChangepushType();
          this.handleChangeImgOrText();
          this.handleActSecon();
          this.getAgainCon(data.userType);
        }
      });
    },
    // 判断是哪种类型，人员或者群组，然后回显
    getAgainCon(val) {
      switch (val) {
        case 1:
          this.changeName = "选择主数据人员";
          this.$refs.send.fetchAgainData(this.form.groupId);
          break;
        case 2:
          this.changeName = "选择主数据群组";
          this.fetchAgainGroupData(this.lableVal.split(",")[1]); // 主数据群组回显
          break;
        case 3:
          this.changeName = "选择Iwork群组";
          break;
        case 4:
          this.changeName = "监控门店类型";
          break;
      }
      this.handleActIsShow("回显");
    },
    // 删除
    // 点击删除或者批量删除
    handleDelete(id) {
      let ids = [];
      if (id) {
        ids = [id];
      } else {
        ids = this.ids;
        if (this.ids.length == 0) {
          this.$message.error("请先选择要删除的选项");
          return false;
        }
      }
      this.$confirm(`您确定要删除吗`, "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          this.$http({
            url: this.$http.adornUrl("/cpcpdu/delete"),
            method: "post",
            data: this.$http.adornData(ids, false),
          }).then(({ data }) => {
            if (data && data.code === 0) {
              this.$message({
                message: "操作成功",
                type: "success",
                duration: 1500,
                onClose: () => {
                  this.fetchTableList();
                },
              });
            } else {
              this.$message.error(data.msg);
            }
          });
        })
        .catch(() => {});
    },
    //推送内容里面的插入变量
    getVariable() {
      this.$http({
        url: this.$http.adornUrl("ydWarn/getColum"),
        method: "get",
        params: this.$http.adornParams({
          unitType: parseInt(this.form.unitType) || "",
        }),
      }).then(({ data }) => {
        // console.log("res=====", res);
        if (data && data.code === 0) {
          console.log("------", data.data);
          this.variableData = data.data;
        } else {
          this.$message.error(data.msg);
        }
      });
    },
    //光标
    testBlur(e) {
      this.blurIndex = e.srcElement.selectionStart;
    },
    //点击插入变量
    bianliangBtn() {
      console.log("=====", this.form.unitType);

      if (this.form.unitType === "" || this.form.unitType === null) {
        console.log("哈哈哈");
        this.$message({
          message: "请选取推送层级",
          type: "info",
          duration: "1000",
        });
        return;
      } else {
        this.bianliangShow = true;
      }
      this.getVariable();
    },
    //点击查看图片按钮
    imgsBtn() {
      console.log("=====", this.form.unitType);
      if (this.form.unitType === "" || this.form.unitType === null) {
        console.log("哈哈哈");
        this.$message({
          message: "请选取推送层级",
          type: "info",
          duration: "1000",
        });
        return;
      } else {
        // this.bianliangShow = true;
        this.imagesType = this.form.unitType;
        this.imageShow = false;
        if (this.form.unitType === "5") {
          this.$message({
            message: "暂无图片",
            type: "info",
            duration: "1000",
          });
        }
      }
    },
    //点击查看升级图片按钮
    imgsShengBtn() {
      if (this.form.unitType === "" || this.form.unitType === null) {
        console.log("哈哈哈");
        this.$message({
          message: "请选取推送层级",
          type: "info",
          duration: "1000",
        });
        return;
      } else {
        // this.bianliangShow = true;
        this.imagesShengType = this.form.unitType;
        // console.log("this.imagesShengType==",this.imagesShengType);
        this.imageShengShow = false;
        // if (this.form.unitType === "5") {
        //   this.$message({
        //     message: "暂无图片",
        //     type: "info",
        //     duration: "1000",
        //   });
        // }
      }
    },

    //确定选择
    onSubmit() {
      // this.checkList = []
      console.log("this.checkList==", this.checkList);
      console.log("this.form.desc====", this.form.desc);
      let checkStr = "";
      let newcheckStr = "";
      this.checkList.forEach((element) => {
        // console.log("element",element);
        checkStr += "${" + element + "},";
      });
      newcheckStr = checkStr.substring(0, checkStr.length - 1);
      console.log("checkStr", checkStr);
      // this.form.desc = this.form.desc + checkStr;
      let index = this.blurIndex;
      let str = this.form.desc;
      this.form.desc = str.slice(0, index) + newcheckStr + str.slice(index);
      console.log("this.form.desc====", this.form.desc);
      this.bianliangShow = false;
      this.checkList = [];
    },
    // 再次提醒
    // 分页
    pageChange(page) {
      this.pageSize = page._pageSize;
      this.pageNum = page._currentPage;
      this.fetchTableList();
    },
    //excel上传
    // 上传成功(热门文章)
    uploadSuccess(response, file, fileList) {
      // console.log("11111111111", response);
      this.uploadForm.batchId = response.data.batchId;
      this.uploadForm.pushNames = response.data.pushNames;
      this.uploadForm.upgradeNames = response.data.upgradeNames;
      this.form.groupId = this.uploadForm.batchId;
      this.personList = this.uploadForm.pushNames; //升级人员
      this.shengjiList = this.uploadForm.upgradeNames; //推送人员
      // console.log("11111111111", response.data.batchId);
      // console.log("11111111111", response.data.pushNames);
      // console.log("11111111111", response.data.upgradeNames);
      // console.log("11111111111", file);
      // console.log("11111111111", fileList);
      if (response.code === 500) {
        this.$message.error(response.msg);
      } else {
        this.$message.success("上传成功");
        // this.getPerson();
      }
    },
    // 上传失败(热门文章)
    uploadError(response, file, fileList) {
      // console.log("2222222222222222");
      // console.log("2222222222222222", response);
      // console.log("2222222222222222", file);
      // console.log("2222222222222222", fileList);
      this.$message.error("上传失败，请联系管理员");
    },
    //模板下载
    downLoad() {
      console.log("推送模板下载");
      console.log(this.action);
      //return
      window.open(this.action);
    },
    //点击触发条件后面的确定
    threSymbol(item) {
      console.log(item);
      this.form.threSymbol = item;
      this.sendStaffAccount();
    },
    subThreshold() {
      console.log("1111", this.form.threSymbol);
      console.log("2222", this.form.triggerCondition);
    },
    // // 设置光标位置
    setCaretPosition(textDom) {
      console.log("22222");
      console.log("textDom", textDom);
      // var cursorPos = 0;
      // if (document.selection) {
      //   // IE Support
      //   textDom.focus();
      //   var selectRange = document.selection.createRange();
      //   selectRange.moveStart("character", -textDom.value.length);
      //   cursorPos = selectRange.text.length;
      // } else if (textDom.selectionStart || textDom.selectionStart == "0") {
      //   // Firefox support
      //   cursorPos = textDom.selectionStart;
      // }
      // return cursorPos;
    },
  },
};
</script>
<style scoped lang="scss">
@import "../../../assets/scss/span_color";
body {
  background-color: rgba(13, 45, 105, 0.6) !important;
}
.el-dialog__wrapper {
  background-color: rgba(13, 45, 105, 0.8) !important;
}
.preview {
  text-align: center;
}
.preview_img {
  text-align: center;
}
.group {
  display: flex !important;
}
.red {
  color: yellow;
}
.green {
  color: green;
}
.cell img {
  width: 50%;
  height: 50%;
}

.button {
  width: 130px;
  height: 40px;
  background: linear-gradient(to bottom, #4eb5e5 0%, #389ed5 100%); /* W3C */
  border: none;
  border-radius: 5px;
  position: relative;
  border-bottom: 4px solid #2b8bc6;
  color: #fbfbfb;
  font-weight: 600;
  font-family: "Open Sans", sans-serif;
  text-shadow: 1px 1px 1px rgba(0, 0, 0, 0.4);
  font-size: 15px;
  text-align: left;
  text-indent: 5px;
  box-shadow: 0px 3px 0px 0px rgba(0, 0, 0, 0.2);
  cursor: pointer;

  /* Just for presentation */
  // display: block;
  margin: 0 auto;
  margin-bottom: 20px;
}
.button:active {
  box-shadow: 0px 2px 0px 0px rgba(0, 0, 0, 0.2);
  top: 1px;
}

.button:after {
  content: "";
  width: 0;
  height: 0;
  display: block;
  border-top: 20px solid #187dbc;
  border-bottom: 20px solid #187dbc;
  border-left: 16px solid transparent;
  border-right: 20px solid #187dbc;
  position: absolute;
  opacity: 0.6;
  right: 0;
  top: 0;
  border-radius: 0 5px 5px 0;
}

/* Button pointing left */

.button.back {
  text-align: right;
  padding-right: 12px;
  box-sizing: border-box;
}
.button.back:after {
  content: "";
  width: 0;
  height: 0;
  display: block;
  border-top: 20px solid #187dbc;
  border-bottom: 20px solid #187dbc;
  border-right: 16px solid transparent;
  border-left: 20px solid #187dbc;
  position: absolute;
  opacity: 0.6;
  left: 0;
  top: 0;
  border-radius: 5px 0 0 5px;
}

/* Single buttons */

.button.site {
  width: 40px;
  text-align: center;
  text-indent: 0;
}
.button.site:after {
  display: none;
}
.threshold_span .el-tag[data-v-76313d94] {
  border: none;
  margin: 0 3px;
  cursor: pointer;
}
.el-textarea {
  width: 92%;
}
.charuBianLiang {
  position: absolute;
  top: -2px;
  right: -5px;
}
.charuImgas {
  position: absolute;
  top: 29px;
  right: -5px;
}
.ShengImgas {
  position: absolute;
  top: 15px;
  right: -5px;
}
// .tuiSong_dialog .el-dialog__body{
//   height: 500px;
//   overflow: auto;
// }
.checkList_box {
  height: 450px;
  overflow: auto;
  margin-bottom: 20px;
  // display: inline-block;
  // display: flex;
  // justify-content: space-around;
  // margin: 0 5px;
}
.checkList_box div {
  margin-left: 20px;
}
.checkList_box /deep/ .el-checkbox__label {
  color: wheat;
}
.onSubmit_button {
  text-align: center;
}
.handleSave_btn {
  text-align: center;
  margin-top: 10px;
}
</style>
